package com.bree.erp.service.stateless;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.bree.erp.entity.BrandSeller;
import com.bree.erp.entity.MasterItem;
import com.bree.erp.entity.Unit;
import com.bree.erp.service.MasterItemService;

@Stateless
public class MasterItemServiceBean implements MasterItemService {

	@PersistenceContext()
	private EntityManager em;

	public MasterItemServiceBean() {

	}

	public MasterItemServiceBean(EntityManager em) {
		this.em = em;
	}

	@Override
	public MasterItem create(BrandSeller seller, String name, String description) {
		MasterItem item = new MasterItem();

		item.setSeller(seller);
		item.setName(name);
		item.setDescription(description);

		em.persist(item);
		return item;
	}

	@Override
	public MasterItem read(Long id) {
		return em.find(MasterItem.class, id);
	}

	@Override
	public MasterItem update(Long id, String name, String description) {

		MasterItem item = read(id);
		item.setName(name);
		item.setDescription(description);

		return item;
	}

	@Override
	public void delete(Long id) {

		MasterItem item = read(id);

		em.remove(item);
	}

	@Override
	public Collection<MasterItem> list() {
		TypedQuery<MasterItem> query = em.createNamedQuery(
				MasterItem.QUERY_SELECT_ALL_MASTERITEM, MasterItem.class);
		return query.getResultList();
	}

	@Override
	public MasterItem update(Long id, BrandSeller seller) {
		MasterItem brand = read(id);
		brand.setSeller(seller);
		return brand;
	}

	@Override
	public MasterItem findByName(String name) {

		TypedQuery<MasterItem> query = em.createNamedQuery(
				MasterItem.QUERY_FINDBYNAME_MASTERITEM, MasterItem.class)
				.setParameter("name", name);

		try {
			return query.getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}

}
